﻿namespace LeetCodeProject._0001_1000._001_100._41_50._042;

public class Solution
{
    public int Trap(int[] height)
    {
        if (height == null || height.Length <= 2)
            return 0;
        var left = 0;
        var right = height.Length - 1;
        var sum = 0;
        while (left < right)
        {
            var leftHeight = height[left];
            var rightHeight = height[right];
            if (leftHeight < rightHeight)
            {
                var i = left + 1;
                while (leftHeight > height[i])
                {
                    sum += leftHeight - height[i];
                    i++;
                }

                left = i;
            }
            else
            {
                var i = right - 1;
                while (rightHeight > height[i])
                {
                    sum += rightHeight - height[i];
                    i--;
                }

                right = i;
            }
        }

        return sum;
    }
}